package middleware

import (
	"blog_go/models/res"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"net/http"
)

func ErrorHandle(c *gin.Context) {
	defer func() {
		if err := recover(); err != nil {
			logrus.Error(err)
			if code, ok := err.(res.ErrorCode); ok {
				res.FailWithCode(code, c)
			} else if err1, ok1 := err.(error); ok1 {
				res.FailWithMessage(err1.Error(), c)
			} else if err2, ok2 := err.(string); ok2 {
				res.FailWithMessage(err2, c)
			} else if err3, ok3 := err.(res.ErrorMsg); ok3 {
				res.FailWithError(err3.Err, err3.Data, c)
			} else {
				c.JSON(http.StatusOK, gin.H{
					"code": res.Error,
					"msg":  err,
					"data": nil,
				})
			}
			c.Abort()
		}
	}()
	c.Next()
}
